package com.yuma.pandc;

import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

public class SynchronousQueueDemo {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> synchronousQueue = new SynchronousQueue<>();
//        synchronousQueue.put("a"); //不存储元素的阻塞队列
//        System.out.println(synchronousQueue.take()); // 阻塞在此，因为此队列不存储




        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(4);
                String data = synchronousQueue.take(); // 阻塞的，直到put()执行才take
                System.out.println(Thread.currentThread().getName()
                        + " 消费: " + data);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "消费者线程").start();

        new Thread(()->{
            try {
                String data = UUID.randomUUID().toString().substring(0, 8); // 3个方法栈
                System.out.println("生产: " + data);
                synchronousQueue.put(data);  // 阻塞的，阻塞到有人take()拿走才往下执行
                System.out.println("放完了....");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "生产者线程").start();
    }
}
